<?php


namespace common\models\service;


use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\TransformApi;
use common\helpers\WeChatApi;
use common\models\Order;
use common\models\OrderGoods;
use common\models\OrderLog;
use common\models\OrderRetreat;
use common\models\System;
use common\models\User;
use yii\helpers\ArrayHelper;

class OrderRetreatService extends OrderRetreat
{
    /**
     * 审核列表
     * @param $where
     * @return array|bool
     */
    public static function getList($where)
    {
        $back = new BaseController();
        $back->model = OrderRetreat::className();
        $return = $back->actionIndex(true, $where, ['create_time' => 'desc']);
        $list = $return['data'];
        //支付状态
        $pay_status = DictCache::get('pay_status');
        //订单状态
        $order_status = DictCache::get('order_status');
        //用户信息
        $delivery_method = DictCache::get('delivery_method');
        $review_status = DictCache::get('review_status');
        $userids = array_unique(ArrayHelper::getColumn($list, 'userid'));
        $userInfo = (new User())->getUserHtml($userids);
        $ids = array_column($list,'order_id');
        $spec = (new OrderGoods())->getHtml($ids);
        $order = Order::find()->where(['id'=>$ids])->select(['pay_amount','total_amount','order_status','id'])->asArray()->all();
        $order = array_column($order,null,'id');
        foreach ($list as $key => $val) {
            $val['pay_status_name'] = $pay_status[$val['pay_status']] ?? '';
            $val['order_status_name'] = $order_status[$val['order_status']] ?? '';
            $val['pay_time'] = $val['pay_time'] ?? '';
            $val['good_html'] = $spec[$val['order_id']]??'';
            $val['user_html'] = $userInfo[$val['userid']]??'';
            $val['delivery_method_title'] = $delivery_method[$val['delivery_method']]??'';
            $val['review_status_title'] = $review_status[$val['review_status']]??'';
            $oneOrder = $order[$val['order_id']]??[];
            $val['order_amount'] = $oneOrder['pay_amount']??0;
            $val['total_amount'] = $oneOrder['total_amount']??0;
            $val['order_status'] = $order_status[$oneOrder['order_status']]??'';
            $list[$key] = $val;
        }
        $return['data'] = $list;
        return $return;
    }

    public static function review($id,$post,$type,$handle_id)
    {
        if (\Yii::$app->request->isGet){
            $info = OrderRetreat::find()->where(['id' => $id])->asArray()->one();
            if (!$info) {
                $back = new BaseController();
                return $back->bError('参数错误');
            }
            $userHtml = (new User())->getUserHtml($info['userid']);
            $userHtml = $userHtml[$info['userid']]??'';
            $review_status = DictCache::get('review_status');
            unset($review_status[0]);
            $info['surplus'] = $info['amount']-$info['already_amount'];
            $info['imgs'] = $info['imgs']?explode(',',$info['imgs']):[];
            return ['info'=>$info,'review_status'=>$review_status,'userHtml'=>$userHtml];
        }
        if (empty($id)){
            return commonApi::message('请选择要审核的记录',false);
        }
        if (empty($post['review_status'])){
            return commonApi::message('请选择审核状态',false);
        }
        if (empty($post['amount'])){
            return commonApi::message('请输入退款金额',false);
        }
        $model = OrderRetreat::findOne($id);
        if ($model->review_status!==0){
            return commonApi::message('请勿重复审核',false);
        }
        if ($model->amount<$post['amount']){
            return commonApi::message('退款金额不能大于申请金额',false);
        }
        $order = Order::find()->where(['order_sn'=>$model->order_sn])->one();
        if ($post['review_status']==1){
            if ($order->party_order&&$order->pay_amount>0){
                $config = System::pay();
                $refundNumber = OrderRetreat::makeOrderid();
                $result = (new WeChatApi($config))->refund($order->party_order,$order->pay_amount,$refundNumber,$post['amount']);
                if (!$result['success']){
                    return $result;
                }
                $model->callback_info = json_encode($result['data']);
                $model->refund_sn = $refundNumber;
            }
            $model->already_amount += $post['amount'];
        }
        $model->review_status = $post['review_status'];
        $model->review_time = date('Y-m-d H:i:s');
        $model->review_remarks = $post['review_remarks']??'';
        $order->refund_status = $post['review_status']+1;
        TransformApi::tx(function ()use ($model,$order,$type,$handle_id){
            if ($model->save()&&$model->save()){
                if ($model->review_status==1){
                    OrderLog::add($type,$order->order_sn,$handle_id,'',"退款成功-".$model->refund_sn,"退款成功-".$model->refund_sn);
                }else{
                    OrderLog::add($type,$order->order_sn,$handle_id,'',"退款拒绝","退款拒绝");
                }
                return commonApi::message('审核成功');
            }
            throw new \Exception('审核失败');
        },$result);
        return $result;
    }
}